package com.bigknow.appstore.proxy.server.impl;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.constant.ConstMessages;
import com.bigknow.appstore.proxy.exceptions.ProxyError;
import com.bigknow.appstore.proxy.exceptions.processor.impl.ErrorHelper;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IChannelProxyToServer;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by chaos on 2016/5/30.
 */
public class HttpChannelProxyToServer implements IChannelProxyToServer {

    private volatile Channel proxyChannel;

    private volatile Channel currentChannel;

    private IProxyServer proxyServer;

    private ICacheManager cacheManager;

    private ILogWriter writer;

    private Bootstrap bootstrap;

    private ProxyTarget proxyTarget;

    private String targetIp;

    private int targetPort;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public HttpChannelProxyToServer(IProxyServer proxyServer, ICacheManager cacheManager
            , ILogWriter writer, Channel proxyChannel
            , String ip, int port, FullHttpRequest msg) {
        this.proxyServer = proxyServer;
        this.cacheManager = cacheManager;
        this.writer = writer;
        this.targetIp = ip;
        this.targetPort = port;
        this.proxyChannel = proxyChannel;
        proxyTarget = new ProxyTarget(this);
        Bootstrap bo = new Bootstrap();
        bo.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, proxyServer.getTimeout())
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new IdleStateHandler(
                                proxyServer.getTimeout(), proxyServer.getTimeout(), proxyServer.getTimeout(), TimeUnit.MILLISECONDS));
                        ch.pipeline().addLast(new HttpResponseDecoder());
                        ch.pipeline().addLast(new HttpRequestEncoder());
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(ConstMessages.DEFAULT_MAX_CONTENT_LENGTH));
                        ch.pipeline().addLast(proxyTarget);
                    }
                });
        ChannelFuture cf = bo.connect(targetIp, targetPort);
        currentChannel = cf.channel();
        cf.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    cf.channel().writeAndFlush(replaceHost(msg, targetIp, targetPort));
                } else {//出现了连接错误，需要抛出
                    try {
                        if (future.cause().getMessage().indexOf("Connection refused") != -1) {
                            ErrorHelper.throwSourceCannotConnError(proxyChannel
                                    , HandlerVariables.requestVoForCurrentResponse.get(currentChannel.id().asLongText())
                                    , future.cause().getMessage()
                            );
                        } else {
                            ErrorHelper.throwSourceError(proxyChannel
                                    , HandlerVariables.requestVoForCurrentResponse.get(currentChannel.id().asLongText())
                                    , future.cause().getMessage());
                        }
                    } catch (ProxyError error) {
                        proxyServer.getErrorProcessor().processError(proxyChannel, error);
                    }
                }
            }
        });
    }

    public void write(FullHttpRequest msg) {
        currentChannel.writeAndFlush(replaceHost(msg, targetIp, targetPort));
    }

    @Override
    public void disConnect() {
        if (currentChannel != null)
            if (HandlerVariables.requestVoForCurrentResponse.containsKey(currentChannel.id().asLongText())) {
                HandlerVariables.requestVoForCurrentResponse.remove(currentChannel.id().asLongText());
            }
        currentChannel.close().awaitUninterruptibly();
        if (bootstrap != null)
            bootstrap.group().shutdownGracefully();
    }

    @Override
    public boolean isActive() {
        return currentChannel.isActive();
    }

    private FullHttpRequest replaceHost(FullHttpRequest request, String targetHost, int port) {
        if(port==80){
            request.headers().set("Host", targetHost);
        }else{
            request.headers().set("Host", targetHost + ":" + port);
        }
        return request;
    }

    public Channel getProxyChannel() {
        return proxyChannel;
    }

    public void setProxyChannel(Channel proxyChannel) {
        this.proxyChannel = proxyChannel;
    }

    public int getTargetPort() {
        return targetPort;
    }

    public void setTargetPort(int targetPort) {
        this.targetPort = targetPort;
    }

    @Override
    public Channel getCurrentChannel() {
        return currentChannel;
    }

    public void setCurrentChannel(Channel currentChannel) {
        this.currentChannel = currentChannel;
    }

    public ProxyTarget getProxyTarget() {
        return proxyTarget;
    }

    public void setProxyTarget(ProxyTarget proxyTarget) {
        this.proxyTarget = proxyTarget;
    }

    public ICacheManager getCacheManager() {
        return cacheManager;
    }

    public void setCacheManager(ICacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    public IProxyServer getProxyServer() {
        return proxyServer;
    }

    public void setProxyServer(IProxyServer proxyServer) {
        this.proxyServer = proxyServer;
    }

    public ILogWriter getWriter() {
        return writer;
    }

    public void setWriter(ILogWriter writer) {
        this.writer = writer;
    }

    public Bootstrap getBootstrap() {
        return bootstrap;
    }

    public void setBootstrap(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    public String getTargetIp() {
        return targetIp;
    }

    public void setTargetIp(String targetIp) {
        this.targetIp = targetIp;
    }


}
